package com.my.socket.nio.v7;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.spi.SelectorProvider;

public class Server {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private ServerSocketChannel serverSocketChannel;
    private Selector acceptSelector;
    private Selector[] readWriteSelectors = new Selector[1];

    public Server(String host, int port) throws Exception {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        this.serverSocketChannel = ServerSocketChannel.open();
        this.serverSocketChannel.configureBlocking(false);
        this.serverSocketChannel.bind(inetSocketAddress);

        SelectorProvider selectorProvider = SelectorProvider.provider();
        this.acceptSelector = selectorProvider.openSelector();
        for (int i = 0; i < this.readWriteSelectors.length; i++) {
            this.readWriteSelectors[i] = selectorProvider.openSelector();
        }
    }

    public void startup() throws Exception {
        new Thread(new AcceptTask(this.serverSocketChannel, this.acceptSelector, this.readWriteSelectors), "accept-thread").start();
        for (int i = 0; i < this.readWriteSelectors.length; i++) {
            new Thread(new ReadWriteTask(this.readWriteSelectors[i]), "read-write-thread-" + i).start();
        }
    }

    public static void main(String[] args) throws Exception {
        String host = "127.0.0.1";
        int port = 9999;
        Server server = new Server(host, port);
        server.startup();
        LOGGER.info("listen at {}:{}", host, port);
    }
}
